package org.example.jwtdemo.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.micrometer.common.util.StringUtils;
import org.example.jwtdemo.entity.Category;
import org.example.jwtdemo.entity.User;
import org.example.jwtdemo.mapper.CategoryMapper;
import org.example.jwtdemo.service.CategoryService;
import org.example.jwtdemo.utils.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public void add(Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        User user = ThreadLocalUtils.get();
        Long id = user.getId();
        category.setCreateUser(Math.toIntExact(id));
        categoryMapper.add(category);
    }

    @Override
    public void delete(List<Integer> ids) {
        categoryMapper.delete(ids);
    }

    @Override
    public List<Category> list() {
        List<Category> list = categoryMapper.list();
        return list;
    }

    @Override
    public void deleteById(Integer id) {
        categoryMapper.deleteById(id);
    }

    @Override
    public PageInfo<Category> selectPage(Category category, Integer pageNum, Integer pageSize) {


        // 声明PageInfo变量在方法作用域内
        PageInfo<Category> pageInfo;
        PageHelper.startPage(pageNum, pageSize);
//        List<Category> page = categoryMapper.selectPage(category);
//        pageInfo = new PageInfo<>(page);
//        // 判断是否有查询参数
        if (category != null && StringUtils.isNotEmpty(category.getCategoryName()) ||
                StringUtils.isNotEmpty(category.getCategoryAlias())) {
            // 有参数，使用条件查询
            // 设置分页参数
            PageHelper.startPage(pageNum, pageSize);
            List<Category> page = categoryMapper.selectPage(category);
            pageInfo = new PageInfo<>(page);
            System.out.println("有参数=========================================");
        } else {
            // 无参数，查询所有
            // 设置分页参数
            PageHelper.startPage(pageNum, pageSize);
            List<Category> list = categoryMapper.list();
            pageInfo = new PageInfo<>(list);
            System.out.println("无参数=========================================");
        }

        // 返回结果
        return pageInfo;
    }


}
